# Complete MP3 test: Create group and upload feature

$baseUrl = "http://localhost:8082/api/voiceprint"
$audioFile = "test_real_mp3.mp3"
$groupId = "test_group_real_mp3"
$featureId = "test_real_mp3_" + (Get-Date -Format "yyyyMMdd_HHmmss")

Write-Host "=== Complete MP3 Test ==="
Write-Host "Audio File: $audioFile"
Write-Host "Group ID: $groupId"
Write-Host "Feature ID: $featureId"
Write-Host ""

# Check if audio file exists
if (-not (Test-Path $audioFile)) {
    Write-Host "Error: Audio file not found: $audioFile"
    exit 1
}

# Step 1: Create group
Write-Host "Step 1: Creating voiceprint group..."
try {
    $createGroupUrl = "$baseUrl/group/create"
    $groupData = @{
        groupId = $groupId
    }
    
    $response = Invoke-RestMethod -Uri $createGroupUrl -Method POST -Body $groupData -ContentType "application/x-www-form-urlencoded"
    Write-Host "Group creation successful!"
    Write-Host "Response: $($response | ConvertTo-Json -Depth 3)"
} catch {
    if ($_.Exception.Response.StatusCode -eq 400) {
        $errorResponse = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($errorResponse)
        $errorText = $reader.ReadToEnd()
        Write-Host "Group creation response: $errorText"
        
        # Check if group already exists
        if ($errorText -like "*already exists*" -or $errorText -like "*已存在*") {
            Write-Host "Group already exists, continuing..."
        } else {
            Write-Host "Group creation failed: $($_.Exception.Message)"
            exit 1
        }
    } else {
        Write-Host "Group creation failed: $($_.Exception.Message)"
        exit 1
    }
}

Write-Host ""

# Step 2: Upload MP3 feature
Write-Host "Step 2: Uploading MP3 feature..."

# Get file size
$fileSize = (Get-Item $audioFile).Length
Write-Host "File size: $fileSize bytes"

# Create multipart form data
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"

$bodyLines = @(
    "--$boundary",
    "Content-Disposition: form-data; name=`"groupId`"",
    "",
    $groupId,
    "--$boundary",
    "Content-Disposition: form-data; name=`"featureId`"",
    "",
    $featureId,
    "--$boundary",
    "Content-Disposition: form-data; name=`"audioFile`"; filename=`"$audioFile`"",
    "Content-Type: audio/mpeg",
    ""
)

$bodyText = $bodyLines -join $LF
$bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($bodyText + $LF)

# Read audio file
$audioBytes = [System.IO.File]::ReadAllBytes($audioFile)

# Create closing boundary
$closingBoundary = [System.Text.Encoding]::UTF8.GetBytes($LF + "--$boundary--" + $LF)

# Combine all parts
$requestBody = New-Object System.Collections.Generic.List[byte]
$requestBody.AddRange($bodyBytes)
$requestBody.AddRange($audioBytes)
$requestBody.AddRange($closingBoundary)

Write-Host "Request body size: $($requestBody.Count) bytes"

try {
    $uploadUrl = "$baseUrl/feature/add"
    
    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=$boundary")
    
    $response = $webClient.UploadData($uploadUrl, "POST", $requestBody.ToArray())
    $responseText = [System.Text.Encoding]::UTF8.GetString($response)
    
    Write-Host "MP3 feature upload successful!"
    Write-Host "Response: $responseText"
    
} catch {
    Write-Host "MP3 feature upload failed: $($_.Exception.Message)"
    Write-Host "Detailed error: $($_.Exception.InnerException.Message)"
} finally {
    if ($webClient) {
        $webClient.Dispose()
    }
}

Write-Host ""
Write-Host "=== Test Completed ==="